package com.general.framework.web.convert;

import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Strings;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

/**
 * @author leejean
 * @ClassName: DateConvert
 * @Description: 日期转换器
 * @date 2020年11月30 17:07:18
 */
public class StringToDateConverter implements Converter<String, Date> {

    public final static DateTimeFormatter CST_DATE_FORMAT = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
    public final static Pattern PATTERN_YY_MM = Pattern.compile("^\\d{4}-\\d{1,2}$");
    public final static Pattern PATTERN_YY_MM_DD = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2}$");
    public final static Pattern PATTERN_YY_MM_DD_HH_MM = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$");
    public final static Pattern PATTERN_YY_MM_DD_HH_SS = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$");

    @Override
    public Date convert(String source) {
        if (Strings.isBlank(source)) {
            return null;
        }
        source = source.trim();
        if (Strings.isNumeric(source)) {
            return new Date(Long.parseLong(source));
        }
        if (Strings.contains(source, "CST")) {
            final LocalDateTime localDateTime = LocalDateTime.parse(source, CST_DATE_FORMAT);
            return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        }
        if (PATTERN_YY_MM.matcher(source).matches()) {
            return Dates.parseDate(source, "yyyy-MM");
        }
        if (PATTERN_YY_MM_DD.matcher(source).matches()) {
            return Dates.parseDate(source, "yyyy-MM-dd");
        }
        if (PATTERN_YY_MM_DD_HH_MM.matcher(source).matches()) {
            return Dates.parseDate(source, "yyyy-MM-dd HH:mm");
        }
        if (PATTERN_YY_MM_DD_HH_SS.matcher(source).matches()) {
            return Dates.parseDate(source, "yyyy-MM-dd HH:mm:ss");
        }
        throw new IllegalArgumentException("Invalid Date value '" + source + "'");
    }

}
